package com.jrx.anytxn.reporting.job.xib.step;

import com.alibaba.fastjson.JSONObject;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.customer.entity.CmCustomerExtInfo;
import com.jrx.anytxn.customer.entity.CmCustomerSecondLevel;
import com.jrx.anytxn.customer.entity.CmLimitChangeLog;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerExtInfoMapper;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerSecondLevelMapper;
import com.jrx.anytxn.customer.service.ICustomerLimitInfoService;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.param.utils.BizTypeProducts;
import com.jrx.anytxn.reporting.config.AnyTxnBatchProperties;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import com.jrx.anytxn.reporting.entity.MEastVStzfxxb;
import com.jrx.anytxn.transaction.entity.AmLoanMainInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @comment: 受托支付信息Processor
 * @author: liuzb
 * @date: 2022/8/23
 */
@Service
public class EntrustmentReportingProcessor implements ItemProcessor<AmLoanMainInfo, MEastVStzfxxb> {

    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private ExtCmCustomerSecondLevelMapper extCmCustomerSecondLevelMapper;
    @Resource
    private AnyTxnBatchProperties anyTxnBatchProperties;
    @Resource
    private ICustomerLimitInfoService iCustomerLimitInfoService;
    @Resource
    private ExtCmCustomerExtInfoMapper extCmCustomerExtInfoMapper;

    private static Logger logger = LoggerFactory.getLogger(EntrustmentReportingProcessor.class);


    @Override
    public MEastVStzfxxb process(AmLoanMainInfo loan) throws Exception {
        try {
            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
            // 指定日期
            Date today = anyTxnBatchProperties.getFileConfig().getToday();
            if (Objects.nonNull(today)) {
                org.setToday(today);
            }
            // 获取当前系统日期
            today = org.getToday();
            MEastVStzfxxb entrustment = new MEastVStzfxxb();
            entrustment.setTenantId(org.getTenantId());
            String customerId = loan.getCustomerId();
            String tenantId = loan.getTenantId();
            entrustment.setCustomerId(customerId);
            // 最早的一笔借据编号
            List<String> seriesProductIds = BizTypeProducts.getSeriesProductIds(loan.getProductId());
            // 获取用户"首笔贷款额度信息"
            CmLimitChangeLog firstLimitInfo = iCustomerLimitInfoService.queryFirstLimitChangeLog(tenantId, customerId, seriesProductIds);
            if (null == firstLimitInfo) {
                logger.info("没有查询到首次额度生效日期，客户id:{},机构id:{}", tenantId, customerId);
                return null;
            }
            String minLoanId = firstLimitInfo.getEtlLoanId();
            //设置信贷合同号
            entrustment.setXdhth(minLoanId);
            // 设置信贷借据号
            entrustment.setXdjjh(minLoanId);
            // 设置币种
            entrustment.setBz("CNY");
            // 设置贷款金额
            entrustment.setDkje(loan.getLoanAmount());
            // 设置受托支付金额
            entrustment.setStzfje(loan.getLoanAmount());
            // 设置受托支付日期
            entrustment.setStzfrq(DateUtils.format(loan.getPostingDate(), DateUtils.DATE_PATTERN_ANOTHER));
            // 扩展字段
            String extFields = loan.getExtFields();
            // 收款信息
            if (StringUtils.isNotBlank(extFields)) {
                JSONObject jsonObject = JSONObject.parseObject(extFields);
                Object recverBankAcctNo = jsonObject.get("RECVER_BANK_ACCT_NO");
                Object recverName = jsonObject.get("RECVER_NAME");
                Object recverBankBankNo = jsonObject.get("RECVER_BANK_BANK_NO");
                Object recverBankFullname = jsonObject.get("RECVER_BANK_FULLNAME");
                // 设置受托支付对象账号
                entrustment.setStzfdxzh(getString(recverBankAcctNo));
                // 设置受托支付对象户名
                entrustment.setStzfdxhm(getString(recverName));
                // 设置受托支付对象行号
                entrustment.setStzfdxhh(getString(recverBankBankNo));
                // 设置受托支付对象行名
                entrustment.setStzfdxxm(getString(recverBankFullname));
            }
            // 受托支付对象账号为空
            if (StringUtils.isBlank(entrustment.getStzfdxzh())) {
                logger.warn("客户:{}的借据编号:{}没有对应受托支付对象账号", customerId, loan.getLoanId());
                return null;
            }
            // 设置采集日期
            entrustment.setCjrq(DateUtils.format(today, DateUtils.DATE_PATTERN_ANOTHER));
            // 获取用户所属的分支行机构信息
            CmCustomerSecondLevel secondLevel = extCmCustomerSecondLevelMapper.selectByCustomerIdAndChannel(customerId, loan.getChannel(), tenantId);
            List<CmCustomerExtInfo> cmCustomerExtInfos = extCmCustomerExtInfoMapper.queryCustomerExtInfos(customerId, tenantId, BizTypeProducts.getSymbolProductId(loan.getProductId()));
            // 设置内部机构号
            String bankOrgNo = secondLevel.getBankOrgNo();
            if (!CollectionUtils.isEmpty(cmCustomerExtInfos)) {
                //获取客户二级信息所属机构号
                bankOrgNo = cmCustomerExtInfos.get(0).getBankOrgNo();
            }
            entrustment.setNbjgh(bankOrgNo);
            return entrustment;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("xibEntrustmentReportingJob 出错了：{}", e.getMessage());
        }
        return null;
    }

    /**
     * 转换成string
     *
     * @param o
     * @return
     */
    public String getString(Object o) {
        return Objects.isNull(o) ? "" : o.toString();
    }
}
